package cool.mtc.security.auth.custom;

import cool.mtc.security.SecurityProperties;
import cool.mtc.security.auth.jwt.JwtAuthFilter;
import cool.mtc.security.handler.auth.DefaultAuthFailureHandler;
import cool.mtc.security.handler.auth.DefaultAuthSuccessHandler;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.stereotype.Component;

/**
 * @author 明河
 */
@Component
@ConditionalOnProperty(value = "mtc.security.auth-custom.enabled", havingValue = "true")
@Setter(onMethod = @__(@Autowired))
public class CustomAuthAdapter extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private SecurityProperties securityProperties;
    private CustomAuthTemplate customAuthTemplate;
    private DefaultAuthSuccessHandler defaultAuthSuccessHandler;
    private DefaultAuthFailureHandler defaultAuthFailureHandler;

    @Override
    public void configure(HttpSecurity http) {
        CustomAuthFilter filter = new CustomAuthFilter(securityProperties);
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        filter.setAuthenticationSuccessHandler(defaultAuthSuccessHandler);
        filter.setAuthenticationFailureHandler(defaultAuthFailureHandler);

        CustomAuthProvider provider = new CustomAuthProvider();
        provider.setAuthTemplate(customAuthTemplate);

        http.authenticationProvider(provider)
                .addFilterBefore(filter, JwtAuthFilter.class);
    }
}
